/*
 * Organizacion de computadoras (66.20) - TP1 1er Cuatrimestre 2013.
 * 
 * Archivo: FileParser.c
 * 
 * Integrantes:
 * 
 *      Maximiliano Monzon (82341)
 *      Nahuel Lucero (90365)
 *      Juan Ignacio Lopez Pecora (84700)
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "FileParser.h"


bool IsAlphanumericCharacter(int c) {
    return ( (c >= 65 && c <= 90) || (c >= 97 && c <= 122) );
}

int _AddWord(tWords *words, char *wordBuffer, unsigned int *countWords, unsigned int *vecSize, unsigned int i) {
    
    if (*countWords == *vecSize) 
    {
        tWords tmp = realloc(*words, sizeof(char*) * (*vecSize) * 2);

        if (!tmp) return false;

        *vecSize *= 2;
        *words = tmp;
    }

    (*words)[*countWords] = (char*)malloc(sizeof(char) * (i + 1));
    strncpy((*words)[*countWords], wordBuffer, i + 1);

    *countWords = *countWords + 1;

    return true;
}

void fileParser(tWords *words, unsigned int *wordsCount, FILE* file ){

    *wordsCount = 0;
    *words = (tWords) malloc(sizeof(char*) * INIT_SIZE);
    
    if (! *words) {
        fprintf(stderr, "\nLa memoria disponible no es suficiente para la ejecucion del programa.");
        exit (EXIT_FAILURE);
    }

    unsigned int vecSize = INIT_SIZE;
    char wordBuffer[WORD_BUFFER];
    int c;
    unsigned int i = 0;

    while ( (c = fgetc(file)) != EOF ) {
        if (!IsAlphanumericCharacter(c)) {
            if (i == 0) continue;
            wordBuffer[i] = '\0';
            if (!_AddWord(words, wordBuffer, wordsCount, &vecSize, i)) return;
            i = 0;
        } 
        else 
            wordBuffer[i++] = c;
    }

    // Ultima palabra
    if (i > 0) {
        wordBuffer[i] = '\0';
        _AddWord(words, wordBuffer, wordsCount, &vecSize, i);
    }
}

void fileParserFromPath(tWords *words, unsigned int* wordsCount, const char* filePath){

    *words = NULL;
    *wordsCount = 0;
    FILE* file = fopen(filePath, "r");

    if (file) {
        fileParser (words, wordsCount, file);
        fclose(file);
    }
    else
    {
        fprintf (stderr, "No se puede abrir el archivo %s", filePath);
    }
}
